import os
import win32con
import win32gui
import win32api
import win32process
import win32com.client


def find_process(exe_name):
    hwnd_list = []
    win32gui.EnumWindows(lambda _hwnd, _hwnd_list: _hwnd_list.append(_hwnd), hwnd_list)
    app_hwnd = 0
    app_pid = 0
    for hwnd in hwnd_list:
        app_pid, procname = get_process_name(hwnd)
        if procname.find(exe_name) > 0:
            app_hwnd = hwnd
            break
    return app_pid, app_hwnd


def get_process_name(hwnd):
    try:
        threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd)
        mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid)
        procname = win32process.GetModuleFileNameEx(mypyproc, 0)
        return procpid, procname
    except:
        return {0, "noprocname"}


def file2title(filename):
    if filename.endswith(".exe"):
        filename = os.path.basename(filename)
    elif filename.endswith(".lnk"):
        shell = win32com.client.Dispatch("WScript.Shell")
        shortcut = shell.CreateShortCut(filename)
        filename = os.path.basename(shortcut.Targetpath)
    app_pid, app_hwnd = find_process(filename)
    if app_hwnd != 0:
        return win32gui.GetWindowText(app_hwnd)
    else:
        return ""
